package com.healthcare.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.healthcare.client.form.ApplyGroupForm;
import com.healthcare.client.mapper.AdminofficeMapper;
import com.healthcare.client.mapper.PatientMapper;
import com.healthcare.client.mapper.TriageagoInfoMapper;
import com.healthcare.client.pojo.*;
import com.healthcare.client.mapper.GroupMapper;
import com.healthcare.client.service.GroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.healthcare.client.utils.SessionUtils;
import com.healthcare.client.vo.AdminConsultationlListVo;
import com.healthcare.client.vo.DoctorConsultationlListVo;
import com.healthcare.client.vo.DoctorMonadVo;
import com.healthcare.client.vo.ReceivingPartyVo;
import com.healthcare.common.constants.ResultCodeEnum;
import com.healthcare.common.exception.KetaiException;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 会诊申请 服务实现类
 * </p>
 *
 * @author 新华医院转诊联盟
 * @since 2020-04-13
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService {

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private AdminofficeMapper adminofficeMapper;

    @Autowired
    private TriageagoInfoMapper triageagoInfoMapper;

    /**
     * 添加会诊信息
     * HW
     *
     * @param applyGroupForm   申请会诊的表单对象
     */
    @Override
    public Map<String, Object> addGroupInfo(ApplyGroupForm applyGroupForm) {
        User user = (User)  SessionUtils.getSessionAttr("doctor");
        // 返回到患者详情的数据
        Map<String,Object> map = new HashMap<>();
        Group group = new Group();
        Patient patient = new Patient();
        BeanUtils.copyProperties(applyGroupForm, group);
        BeanUtils.copyProperties(applyGroupForm, patient);
        // 判断转诊数据是否为空
        if(StringUtils.isEmpty(group)){
            throw  new KetaiException(25555,"会诊信息为空");
        }
        // 判断患者数据是否为空
        if(StringUtils.isEmpty(patient)){
            throw  new KetaiException(25556,"患者信息为空");
        }

        group.setState(0);
        group.setOperator(user.getUsername());
        patient.setOperator(user.getUsername());
        // 判断重新预约会诊(没有id代表申请，有则重新申请)
        if(!StringUtils.isEmpty(applyGroupForm.getId()) && !StringUtils.isEmpty(applyGroupForm.getPatientId())){
            //修改
            patientMapper.updateById(patient);
            baseMapper.updateById(group);
        }else {
            //添加
            patientMapper.insert(patient);
            group.setSuffererDetailsId(patient.getPatientId());
            baseMapper.insert(group);
        }


        map.put("group",group);
        map.put("patient",patient);
        return map;
    }

    /**
     * 取消会诊
     * HW
     *
     * @param groupId 会诊id
     */
    @Override
    public void cancelConsultation(Integer groupId) {
        Group group = baseMapper.selectById(groupId);
        patientMapper.deleteById(group.getSuffererDetailsId());
        baseMapper.deleteById(groupId);
    }

    /**
     * 完成会诊
     * HW
     *
     * @param groupId  会诊id
     * @param identity 身份区分0 - 1
     */
    @Override
    public void accomplishGroup(Integer groupId,Integer identity) {
        User user = null;
        //医生
        if (identity == 1){
            user = (User)  SessionUtils.getSessionAttr("doctor");
        }
        //小助手
        if (identity == 0){
            user = (User)  SessionUtils.getSessionAttr("admin");
        }
        Group group = new Group();
        group.setId(groupId);
        group.setState(3);
        group.setSuccessfulTime(new Date());
        group.setOperator(user.getUsername());
        baseMapper.updateById(group);
    }

    /**
     * 拒绝会诊
     * HW
     *
     * @param groupId     会诊id
     * @param groupRemark 拒绝理由
     */
    @Override
    public void refuseGroup(Integer groupId, String groupRemark) {
        User user = (User)  SessionUtils.getSessionAttr("admin");
        Group group = new Group();
        group.setId(groupId);
        group.setState(2);
        group.setRefusedTime(new Date());
        group.setGroupRemark(groupRemark);
        group.setOperator(user.getUsername());
        baseMapper.updateById(group);
    }

    /**
     * 撤销操作
     * HW
     *
     * @param groupId 会诊id
     */
    @Override
    public void revocationGroupOperation(Integer groupId) {
        User user = (User)  SessionUtils.getSessionAttr("admin");
        Group group = new Group();
        group.setId(groupId);
        group.setState(0);
        group.setOperator(user.getUsername());
        baseMapper.updateById(group);
    }

    /**
     * 撤销分诊
     * HW
     *
     * @param groupId 会诊id
     */
    @Override
    public void revocationTriageGroup(Integer groupId) {
        User user = (User)  SessionUtils.getSessionAttr("admin");
        Group group = new Group();
        //查询是否有分诊前信息
        QueryWrapper<TriageagoInfo> triageagoInfoQueryWrapper = new QueryWrapper<>();
        triageagoInfoQueryWrapper.eq("group_id",groupId);
        triageagoInfoQueryWrapper.eq("is_deleted","0");
        TriageagoInfo triageagoInfo = triageagoInfoMapper.selectOne(triageagoInfoQueryWrapper);
        if (!StringUtils.isEmpty(triageagoInfo) && !StringUtils.isEmpty(triageagoInfo.getId())){
            //还原会诊信息
            group.setDepartmentId(triageagoInfo.getDepartmentId());
            group.setAppointmentTime(triageagoInfo.getAppointmentTime());
            //删除分诊前信息
            triageagoInfoMapper.deleteById(triageagoInfo);
        }
        group.setId(groupId);
        group.setState(0);
        group.setOperator(user.getUsername());
        baseMapper.updateById(group);
    }

    /**
     * 分诊操作
     * HW
     *
     * @param group 分诊信息
     */
    @Override
    public void triageGroup(Group group) {
        User user = (User)  SessionUtils.getSessionAttr("admin");
        //添加会诊分诊前的信息
        Group groupTriageagoInfo = baseMapper.selectById(group.getId());
        TriageagoInfo triageagoInfo = new TriageagoInfo();
        triageagoInfo.setGroupId(groupTriageagoInfo.getId());
        triageagoInfo.setDepartmentId(groupTriageagoInfo.getDepartmentId());
        triageagoInfo.setAppointmentTime(groupTriageagoInfo.getAppointmentTime());
        triageagoInfo.setOperator(user.getUsername());
        triageagoInfoMapper.insert(triageagoInfo);
        //修改会诊状态
        group.setState(1);
        group.setGroupTime(new Date());
        group.setOperator(user.getUsername());
        baseMapper.updateById(group);
    }

    /**
     * 分页会诊列表数据
     *
     * @param page        当前页
     * @param size        分页显示数
     * @param identity    身份区分0 - 1
     * @param sortType    排序方式：0-默认、1-预约时间、2-患者姓名、3-沟通记录
     * @param patientname 搜索患者姓名
     * @return
     */
    @Override
    public PageInfo getGroupListVo(Integer page, Integer size, Integer identity, Integer sortType, String patientname) {
        // 当身份为操作员时
        if (identity == 0){
            // 获取session的值
            Object object =  SessionUtils.getSessionAttr("admin");
            // 判断session值是否为空,如果为空则抛出异常
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
            // 保存返回数据的list vo
            List<AdminConsultationlListVo> listVoList = null;
            // 通过pagehelper 进行拦截 分页
            PageHelper.startPage(page,size);
            listVoList = baseMapper.getAdminGroupListVo(sortType, patientname);
            PageInfo<AdminConsultationlListVo> pageInfo = new PageInfo<AdminConsultationlListVo>(listVoList);
            return pageInfo;
        }
        // 当身份为医生时
        if (identity == 1){
            // 保存返回数据的list vo
            List<DoctorConsultationlListVo> listVoList = null;
            // 通过pagehelper 进行拦截 分页
            PageHelper.startPage(page,size);
            // 获取session的值
            Object object =  SessionUtils.getSessionAttr("doctor");
            // 判断session值是否为空,如果为空则抛出异常
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
            User user = (User) object;
            // 如果医生有值
            if(!StringUtils.isEmpty(user)){
                listVoList =  baseMapper.getGroupListVo(user.getId(),sortType, patientname);
            }
            PageInfo<DoctorConsultationlListVo> pageInfo = new PageInfo<DoctorConsultationlListVo>(listVoList);
            return pageInfo;
        }
        return null;
    }

    /**
     * 根据会诊单id,得到会诊单得所有信息
     *
     * @param groupId 会诊单id
     * @return
     */
    @Override
    public List<DoctorMonadVo> getDoctorMonadVoList(Integer groupId) {
        List<DoctorMonadVo> doctorMonadVoList = baseMapper.getDoctorMonadVoList(groupId);
        DoctorMonadVo doctorMonadVo = doctorMonadVoList.get(0);
        //获得会诊所有科室id
        String[] departmentIdArr = doctorMonadVo.getDepartmentId().split(",");
        List<Adminoffice> adminofficeList = adminofficeMapper.selectAdminofficeByIdList(departmentIdArr);
        //获得所有接诊医生姓名
        List<String> groupDoctorList = new ArrayList<>();
        if (doctorMonadVo.getGroupDoctor() != null){
            groupDoctorList = Arrays.asList(doctorMonadVo.getGroupDoctor().split(",")) ;
        }
        List<ReceivingPartyVo> receivingPartyVoList = new ArrayList<>();
        if (adminofficeList.size() == groupDoctorList.size()){
            //填充
            for (int i = 0; i < adminofficeList.size(); i++) {
                ReceivingPartyVo receivingPartyVo = new ReceivingPartyVo();
                receivingPartyVo.setAdminofficeName(adminofficeList.get(i).getAdminofficename());
                receivingPartyVo.setGroupDoctor(groupDoctorList.get(i));
                receivingPartyVoList.add(receivingPartyVo);
            }
        }
        doctorMonadVo.setReceivingPartyVoList(receivingPartyVoList);
        return doctorMonadVoList;
    }

    /**
     * 通过会诊id获得会诊与患者信息
     *
     * @param groupId
     * @return
     */
    @Override
    public Map<String, Object> getGroupPatientInfo(Integer groupId) {
        Map<String,Object> map = new HashMap<>();
        Group group = baseMapper.selectById(groupId);
        Patient patient = patientMapper.selectById(group.getSuffererDetailsId());

        map.put("group",group);
        map.put("patient",patient);
        return map;
    }

}
